/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    TreeNode ans = null;
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        def(root,p,q);
        return ans;
    }

    public boolean def(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) return false;
        boolean l = def(root.left,p,q);
        boolean r = def(root.right,p,q);
        if((l && r) || ((root.val == p.val || root.val == q.val) && (l || r))) {
            ans = root;
        }
        return l || r || (root.val == p.val || root.val == q.val);
    }
}